package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.core.text.CharsetKit;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.CheckInConfig;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.domain.Elder;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import com.zzyl.utils.CodeGenerator;
import com.zzyl.utils.IDCardUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.domain.CheckIn;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住信息Service业务层处理
 *
 * @author zouguangghuan
 * @date 2025-10-21
 */
@Slf4j
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住信息
     *
     * @param id 入住信息主键
     * @return 入住信息
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住信息列表
     *
     * @param checkIn 入住信息
     * @return 入住信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住信息
     *
     * @param ids 需要删除的入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息信息
     *
     * @param id 入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private ElderMapper elderMapper;


    /**
     * 入住办理
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo()));
        //判断是否入住
        if (null != elder) {
            if (elder.getStatus() >= 2 && elder.getStatus() <= 4) { //老人已入住
                throw new ServiceException("该老人已入住");
            }
        }
        //老人未入住
        int rows = bedMapper.updateBedStatus(checkInApplyDto.getCheckInConfigDto().getBedId());
        if (rows == 0) {
            throw new ServiceException("该床位有人，请选择其他床位");
        }

        //老人不存在则新增老人信息，存在则更新老人信息
        Elder newElder = saveOrUpdateElder(checkInApplyDto, elder);
        //保存入住信息
        CheckIn checkIn = addCheckIn(checkInApplyDto, newElder);
        //保存入住配置信息
        addCheckConfig(checkInApplyDto, checkIn);
        //保存入住合同信息
        addContract(checkInApplyDto, checkIn);
    }

    //查询入住详情信息
    @Override
    public CheckInDetailVo detail(Long id) {
        //查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        //查询老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        //查询合同信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getCheckInId, id));
        //查询入住配置信息
        CheckInConfig config = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, id));

        //封装老人信息
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        checkInElderVo.setAge(IDCardUtils.getAgeByIdCard(elder.getIdCardNo()));
        //封装入住配置信息
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(config, CheckInConfigVo.class);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        //封装家属信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
        log.info("老人家属列表：{}", elderFamilyVoList);
        //封装最终响应数据
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        log.info("最终响应数据：{},", checkInDetailVo);
        return checkInDetailVo;
    }


    //保存入住信息
    private CheckIn addCheckIn(CheckInApplyDto checkInApplyDto, Elder newElder) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(newElder.getId());
        checkIn.setElderName(newElder.getName());
        checkIn.setIdCardNo(newElder.getIdCardNo());
        checkIn.setBedNumber(newElder.getBedNumber());

        checkIn.setStatus(1);  //未入住
        checkIn.setCreateTime(new Date());
        checkIn.setUpdateTime(checkIn.getCreateTime());
        //设置紧急联系人
        //remark，老人的家属联系人,转成json字符串
        String jsonStr = JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList());
        checkIn.setRemark(jsonStr);
        //获取入住配置信息
        CheckInConfigDto config = checkInApplyDto.getCheckInConfigDto();
        checkIn.setStartDate(config.getStartDate());
        checkIn.setEndDate(config.getEndDate());
        checkIn.setNursingLevelName(config.getNursingLevelName());
        save(checkIn);
        return checkIn;
    }

    //保存入住配置信息
    private void addCheckConfig(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckInConfig config = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        config.setCheckInId(checkIn.getId());
        config.setCreateTime(new Date());
        config.setUpdateTime(config.getCreateTime());

        checkInConfigMapper.insert(config);
    }

    //保存入住合同信息
    private void addContract(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setCheckInId(checkIn.getId());
        contract.setElderId(checkIn.getElderId());
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderName(checkIn.getElderName());
        contract.setStartDate(checkIn.getStartDate());
        contract.setEndDate(checkIn.getEndDate());
        contract.setStatus(0);  //未生效
        contract.setCreateTime(new Date());
        contract.setUpdateTime(contract.getCreateTime());

        contractMapper.insert(contract);
    }


    //保存或更新老人信息
    private Elder saveOrUpdateElder(CheckInApplyDto checkInApplyDto, Elder elder) {
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        Elder newElder = BeanUtil.toBean(checkInElderDto, Elder.class);

        //获取床的id，用来通过此id获取床的编号
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        //获取到床的编号
        String bedNumber = bedMapper.selectBedById(bedId).getBedNumber();
        //设置床的id和编号
        newElder.setBedId(bedId);
        newElder.setBedNumber(bedNumber);
        //设置老人状态为启用
        newElder.setStatus(1);
        //判断老人是否存在（就是老人之前是否有入住历史，有的话就有老人的信息）
        if (elder != null) {
            //更新老人信息
            newElder.setUpdateTime(new Date());
            newElder.setId(elder.getId());
            elderMapper.updateById(newElder);
        } else {
            //新增老人信息
            newElder.setCreateTime(new Date());
            newElder.setUpdateTime(new Date());
            elderMapper.insert(newElder);
        }
        return newElder;
    }
}
